package com.itheima.servlet;


import com.github.pagehelper.PageInfo;
import com.itheima.domain.Emp;
import com.itheima.service.EmpService;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/emp/*")
public class EmpServlet extends BaseServlet {
    private Emp emp = new Emp();

    private EmpService service = new EmpService();
    protected void listByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNum = "1";
        if(req.getParameter("page")!=null)
            pageNum = req.getParameter("page");
        List<Emp> list = service.findByPage(pageNum);
        PageInfo<Emp> pageInfo=new PageInfo<Emp>(list);
        req.setAttribute("list",list);
        req.setAttribute("pageInfo",pageInfo);
        req.getRequestDispatcher("/page/main.jsp").forward(req,resp);
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String empno = req.getParameter("empno");
        service.deleteById(empno);
        resp.sendRedirect(req.getContextPath() + "/emp/listByPage");
    }

    protected void beforeUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        refreshEmp(req);
        req.setAttribute("emp",emp);
        req.getRequestDispatcher("/page/operate.jsp").forward(req,resp);
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        refreshEmp(req);
        service.update(emp);
        resp.sendRedirect(req.getContextPath() + "/emp/listByPage");
    }

    private void refreshEmp(HttpServletRequest req) {
        String empno = req.getParameter("empno");
        String ename = req.getParameter("ename");
        String job = req.getParameter("job");
        String hireDate = req.getParameter("hireDate");
        String sal = req.getParameter("sal");
        //emp = new Emp(Integer.parseInt(empno), ename, job, hireDate, Double.parseDouble(sal));
        emp.setSal(Double.parseDouble(sal));
        emp.setEmpno(Integer.parseInt(empno));
        emp.setEname(ename);
        emp.setHireDate(hireDate);
        emp.setJob(job);
    }
}
